package com.gxa.meiye.admin.realm;

import com.gxa.meiye.core.utils.MD5Util;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;


/**
 * @author chen
 * @date 2022/6/28 16:14
 */
@Component
public class AdminRealm extends AuthorizingRealm {

//    @Autowired
//    IRoleBOService roleBOService = null;

    // 授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户手机号
        String phone = (String)principalCollection.getPrimaryPrincipal();
        System.out.println("授权过程中获取用户的手机号:"+phone);

        //添加角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 查询角色信息 roleList
       /* LambdaQueryWrapper<RoleBO>  lambda = Wrappers.lambdaQuery(RoleBO.class);
        lambda.eq(RoleBO::getPhone,phone);
        List<RoleBO> list = roleBOService.list(lambda);
        for (RoleBO roleBO : list) {
            info.addRole(roleBO.getName());
        }*/
        //应该用数据库查询注入进来的

        info.addRole("admin");
        info.addRole("manager");

        // TODO 查询权限信息 permissionList
        info.addStringPermission("user:add");
        info.addStringPermission("user:delete");
        info.addStringPermission("permission:delete");
        info.addStringPermission("permission:add");


        // 返回已经完成绑定(角色信息和权限信息)的授权信息对象
        return info;
    }


    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String phone = (String) authenticationToken.getPrincipal();
        System.out.println("认证过程中获取用户的手机号:"+phone);

        //TODO 通过声明service业务实现根据手机号查询admin用户密码的功能
     /*   AdminBO adminBO = new AdminBO();
        adminBO.setPwd("123456");
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(phone,adminBO.getPwd(), getName());*/
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(phone, MD5Util.encode("123456"), getName());
        return info;
    }

}
